class Solution
{
public:
    long long taskSchedulerII(vector<int> &tasks, int space)
    {
        unordered_map<int, long long> lastFinishDay;
        long long day = 1;
        for (int task : tasks)
        {
            if (lastFinishDay.count(task))
            {
                if (day - lastFinishDay[task] <= space)
                {
                    day = lastFinishDay[task] + space + 1;
                }
                else
                {
                    ++day;
                }
            }
            else
            {
                ++day;
            }
            lastFinishDay[task] = day;
        }
        return day - 1;
    }
};